﻿namespace Microsoft.VisualStudio.IDE.ToolboxControlsInstaller
{
    using Microsoft.Win32;
    using System;
    using System.Collections.Generic;
    using System.Reflection;

    internal class CachedAssemblyFolder : AssemblyFolder
    {
        private List<RegisteredAssembly> _assemblies;
        private readonly RegistryKey _cacheKey;

        private CachedAssemblyFolder(RegistryKey cacheKey)
        {
            this._cacheKey = cacheKey;
        }

        public override IEnumerable<RegisteredAssembly> GetAssemblies()
        {
            if (this._assemblies == null)
            {
                this._assemblies = new List<RegisteredAssembly>();
                foreach (string str in this._cacheKey.GetSubKeyNames())
                {
                    using (RegistryKey key = this._cacheKey.OpenSubKey(str))
                    {
                        RegisteredAssembly assembly;
                        string strA = key.GetValue("AssemblyType") as string;
                        if (string.Compare(strA, SilverlightAssembly.StaticIdentifier, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            assembly = new SilverlightAssembly(new AssemblyName(str));
                        }
                        else if (string.Compare(strA, WPFAssembly.StaticIdentifier, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            assembly = new WPFAssembly(new AssemblyName(str));
                        }
                        else
                        {
                            assembly = new DotNetAssembly(new AssemblyName(str));
                        }
                        assembly.DefaultCategory = key.GetValue("DefaultCategory") as string;
                        assembly.TargetFramework = this._cacheKey.GetValue("TargetFramework") as string;
                        assembly.RegistryHash = key.GetValue("AssemblyHash") as byte[];
                        assembly.AssemblyName.CodeBase = key.GetValue("Codebase") as string;
                        this._assemblies.Add(assembly);
                    }
                }
            }
            return this._assemblies;
        }

        public static CachedAssemblyFolder GetCache(RegistryKey userSettings, string key)
        {
            RegistryKey cacheKey = userSettings.OpenSubKey(@"ToolboxControlsInstaller_AssemblyFoldersExCache\" + key.Replace('\\', '_'));
            if (cacheKey == null)
            {
                return null;
            }
            return new CachedAssemblyFolder(cacheKey);
        }

        public byte[] RegistryHash
        {
            get
            {
                return (this._cacheKey.GetValue("RegistryHash") as byte[]);
            }
        }
    }
}

